package overlay;

import java.io.File;
import java.net.URI;
import java.net.URISyntaxException;

import net.jxta.document.AdvertisementFactory;
import net.jxta.id.IDFactory;
import net.jxta.pipe.PipeID;
import net.jxta.pipe.PipeService;
import net.jxta.platform.NetworkManager;
import net.jxta.protocol.PipeAdvertisement;

public class OverlayManager {
	
    public final static String SOCKETIDSTR = "urn:jxta:uuid-59616261646162614E5047205032503393B5C2F6CA7A41FDB0F890173088E79404";
    /**
     * Creates a Socket Pipe Advertisement with the pre-defined pipe ID
     * @return a socket PipeAdvertisement
     */
    public static PipeAdvertisement getSocketAdvertisement() {
        PipeID socketID = null;

        try {
            socketID = (PipeID) IDFactory.fromURI(new URI(SOCKETIDSTR));
        } catch (URISyntaxException use) {
            use.printStackTrace();
        }
        PipeAdvertisement advertisement = (PipeAdvertisement) AdvertisementFactory.newAdvertisement(PipeAdvertisement.getAdvertisementType());

        advertisement.setPipeID(socketID);
        // set to type to propagate
        advertisement.setType(PipeService.PropagateType);
        advertisement.setName("Socket tutorial");
        return advertisement;
    }

	/**
	 * Apenas inicia o JXTA em modo rendezvous e relay, esperando os proxys se conectarem
	 * Isso possibilita a comunicação de máquinas mesmo que estejam atras de NAT.
	 * 
	 */
	public static void main(String[] args) {
        NetworkManager manager = null;

        try {
            manager = new NetworkManager(NetworkManager.ConfigMode.RENDEZVOUS_RELAY, "OverlayManager", new File(new File(".cache"), "OverlayManager").toURI());
            System.out.println("Starting JXTA");
            manager.startNetwork();
            System.out.println("JXTA Started");
        } catch (Exception e) {
            e.printStackTrace();
            System.exit(-1);
        }
        System.out.println("Waiting peers");
        while (true) {
	        try {
				Thread.sleep(Integer.MAX_VALUE);
			} catch (InterruptedException e) {
			}
		}
//        System.out.println(MessageFormat.format("Connected :{0}", connected));
//        System.out.println("Stopping JXTA");
//		  manager.stopNetwork();
	}
	
}
